package cn.demomaster.quickrouter.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

import androidx.customview.widget.ViewDragHelper;

import cn.demomaster.quickrouter.R;
import cn.demomaster.quickrouter.fragment.QuickPage;

/**
 * 适用于用于fragment页面切换
 * 可拖动子布局
 */
public class QuickPageDragFrameLayout extends FrameLayout {

    private static final String TAG = QuickPageDragFrameLayout.class.getSimpleName();

    // private QuickViewDragHelper quickViewDragHelper;
    private QuickViewDragHelper mViewDragHelper;

    private MyDragCallback mDragCallback;
    private ViewDragHelper.Callback mDragCallback2;

    public QuickPageDragFrameLayout(Context context) {
        this(context, null);
    }

    public QuickPageDragFrameLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public QuickPageDragFrameLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        initDragCallBack();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // 锁屏后再点亮屏幕会调用一下onLayout，不加判断会让布局还原(为什么???)
        if (changed) {
            super.onLayout(changed, l, t, r, b);
        }
    }

    private void initDragCallBack() {
        mDragCallback = new MyDragCallback();
        mViewDragHelper = QuickViewDragHelper.create(this, 1.0f, mDragCallback);// ViewDragHelper.create(this, 1.0f, this);
        // 设置为可以捕获屏幕左边的滑动
        mViewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
    }

    @Override
    public void computeScroll() {
        if (mViewDragHelper != null && mViewDragHelper.continueSettling(true)) {
            invalidate();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return mViewDragHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mViewDragHelper.processTouchEvent(event);
        return true;
    }

    public void setDragCallback(MyDragCallback mDragCallback) {
        this.mDragCallback = mDragCallback;
    }

    Object contextObject;

    public void setContextObject(Object o) {
        contextObject = o;
    }

    boolean dragFinish;

    /*————————————————————————————————————————————————————————————————————————————*/


    private class MyDragCallback extends QuickViewDragHelper.Callback {

        /**
         * 返回true，表示传入的View可以被拖动
         */
        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            // 只允许第一个被拖动
            return child.equals(getChildAt(0));
        }

        /**
         * 传入View即将到达的位置(left)，返回值为真正到达的位置
         */
        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            LayoutParams lp = (LayoutParams) child.getLayoutParams();
            int leftBorder = getPaddingLeft() + lp.leftMargin;
            int rightBorder = getMeasuredWidth() - getPaddingRight() - child.getMeasuredWidth() - lp.rightMargin;
            //return Math.min(Math.max(leftBorder, left), rightBorder);
            return Math.max(0,left);
        }

        /**
         * 传入View即将到达的位置(top)，返回值为真正到达的位置
         */
        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
            return 0;
        }

        /**
         * 返回横向能拖动的长度，默认返回0，如果被拖动的View设置了点击事件，返回0会不响应点击事件
         */
        @Override
        public int getViewHorizontalDragRange(View child) {
            return getMeasuredWidth() - child.getMeasuredWidth();
        }

        /**
         * 返回纵向能拖动的长度，默认返回0，如果被拖动的View设置了点击事件，返回0会不响应点击事件
         */
        @Override
        public int getViewVerticalDragRange(View child) {
            return getMeasuredHeight() - child.getMeasuredHeight();
        }

        @Override
        public void onEdgeDragStarted(int edgeFlags, int pointerId) {
            Log.i(TAG, "onEdgeDragStarted;" + edgeFlags);
            // 当从屏幕左边开始滑动的时候，开始滑动第一个子控件
            mViewDragHelper.captureChildView(getChildAt(0), pointerId);
        }

        /**
         * 当手指离开以后的回调
         *
         * @param releasedChild 子View
         * @param xvel          X轴的速度
         * @param yvel          Y轴的速度
         */
        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            if (releasedChild.equals(getChildAt(0))) {
                Log.i(TAG, "xvel = " + xvel + ",yvel=" + yvel);
                if (xvel > getMeasuredWidth() / 2) {
                    dragFinish = true;
                    mViewDragHelper.settleCapturedViewAt( getMeasuredWidth() , 0);
                }else {
                    // 手指松开以后自动回到原始位置
                    mViewDragHelper.settleCapturedViewAt(0, 0);
                }
                invalidate();
            }
        }

        /**
         * 当某一个View在动的时候的回调，不管是用户手动滑动，还是使用settleCapturedViewAt或者smoothSlideViewTo，都会回调这里
         */
        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            Log.i(TAG, "left=" + left + ",top=" + top + ",dx=" + dx + ",dy=" + dy);
            if (changedView.equals(getChildAt(0))) {
                if (left == getMeasuredWidth() && top == 0 && dragFinish) {
                    if (contextObject instanceof QuickPage) {
                        ((QuickPage) contextObject).onDragFinish();
                    }
                }
            }
            int backgroundColor = getResources().getColor(R.color.transparent_dark_33);
            int red = (backgroundColor >> 16) & 0xFF;
            int green = (backgroundColor >> 8) & 0xFF;
            int blue = backgroundColor & 0xFF;
            int alpha = (int) ((1-left/(getMeasuredWidth()*1f)) * 100); // 透明度范围为0-255，0表示完全透明，255表示完全不透明
//            String colorString = String.format("#%02X%02X%02X%02X", (1-left/getMeasuredWidth()) * 255,red, green, blue);//去除了透明度
//            Drawable drawable = new ColorDrawable(Color.parseColor(colorString));
//            setBackground(drawable);

            // 根据颜色和透明度创建Color对象
            int color = Color.argb(alpha,red, green, blue);
            Drawable drawable = new ColorDrawable(color);
            setBackground(drawable);
        }
    }

}
